/*
 * @Description:
 * @Autor: Chen
 * @Date: 2020-01-21 14:30:41
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-05-26 14:23:27
 */
import { Injectable, Inject } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { catchError, Observable, of, tap } from 'rxjs';
import { API_CONFIG_ADMIN, API_CONFIG_HOME } from '../services.module';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router } from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    @Inject(API_CONFIG_ADMIN) private uri: string,
    @Inject(API_CONFIG_HOME) private host: string,
    private router: Router,
    private modalServe: NzModalService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let authReq: HttpRequest<any>;
    if (req.url.indexOf('https') === -1 && req.url.indexOf('http') === -1) {
      authReq = req.clone({
        url: this.uri + req.url,
        headers: req.headers.set('withCredentials', 'true')
      });
    } else {
      authReq = req;
    }
    return next
      // 返回处理后的请求
      .handle(authReq)
      // 返回结果错误处理
      .pipe(
        tap(
          event => {
            if (event instanceof HttpResponse) {
              const response = event.body;
              if (event.status !== 200) {
                this.modalServe.create({
                  nzTitle: '提示信息',
                  nzContent: response.message,
                  nzFooter: null,
                  nzStyle: { top: '250px' },
                  nzOnCancel: () => { this.router.navigate(['/home']); }
                });
                throw (event.statusText);
              }
              if (typeof response === 'string') {
                return response;
              } else if (typeof response === 'object') {
                return of(new HttpResponse(Object.assign(event.body, response)));
              } else {
                return response;
              }
            }
            return;
          },
          error => {
            throw (error.message);
          }
        ),
        catchError(err => of(err))
      );
  }
}
